package com.molichuxing.gateway.api.services.impl;

import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.molichuxing.framework.exception.BizException;
import com.molichuxing.framework.result.ResponseCodeEnum;
import com.molichuxing.framework.result.ResponseResult;
import com.molichuxing.framework.utils.IpUtil;
import com.molichuxing.gateway.api.services.PaymentApiService;
import com.molichuxing.gateway.bff.payment.entity.request.create.OrderPayCreateVo;
import com.molichuxing.gateway.bff.payment.entity.request.modify.AioPayResultModifyVo;
import com.molichuxing.gateway.bff.payment.entity.response.CashierDeskVo;
import com.molichuxing.gateway.bff.payment.entity.response.PaymentRecordVo;
import com.molichuxing.gateway.bff.payment.entity.response.PaymentResultVo;
import com.molichuxing.gateway.bff.payment.services.PaymentBffService;
import com.molichuxing.gateway.bff.payment.services.PaymentResultBffService;
import com.molichuxing.gateway.bff.user.entity.response.UserVo;
import com.molichuxing.gateway.utils.redis.TokenUtil;
import com.molichuxing.services.property.PaymentCostTypeEnum;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

@Api(tags = "支付相关接口")
@RestController
@RequestMapping(value = "/payment")
public class PaymentApiServiceImpl extends RootApiService implements PaymentApiService {
	private static final Logger logger = LoggerFactory.getLogger(PaymentApiServiceImpl.class);

	@Resource
	private TokenUtil tokenUtil;

	@Resource
	private PaymentBffService paymentBffService;

	@Resource
	private PaymentResultBffService paymentResultBffService;

	@Override
	@ApiOperation(value = "收银台")
	@ApiImplicitParams({ @ApiImplicitParam(name = "orderCode", value = "订单号", required = true, dataType = "Long"),
			@ApiImplicitParam(name = "scheduleId", value = "排期id(还款传)", required = false, dataType = "Integer"),
			@ApiImplicitParam(name = "payType", value = "支付类型（1：订购，2：续订，3：加购，4：结算，5：还款，6：退租缴费）", required = true, dataType = "Integer") })
	@GetMapping(value = "/casher")
	public ResponseResult<CashierDeskVo> cashierDesk(@RequestHeader(value = "token", required = true) String token,
			Long orderCode, Integer scheduleId, Integer payType) {
		ResponseResult<CashierDeskVo> result = new ResponseResult<>();
		try {
			// 根据token获取用户信息
			UserVo user = tokenUtil.getUser(token);
			if (scheduleId != null && scheduleId > 0) {
				payType = 5;
			}
			result.success(paymentBffService.getCashierDesk(orderCode, PaymentCostTypeEnum.getEnum(payType), scheduleId,
					user.getUserId()));

		} catch (BizException e) {
			logger.error("[cashierDesk]收银台信息异常:", e);
			result.error(e.getExceptionCode() == null ? ResponseCodeEnum.UNKNOWN_ERROR.getCode() : e.getExceptionCode(),
					e.getMessage());
		} catch (Exception e) {
			logger.error("[cashierDesk]收银台信息异常:", e);
			result.error("收银台信息异常");
		}
		return result;
	}

	@SuppressWarnings("unchecked")
	@Override
	@ApiOperation(value = "支付(生成预支付单)")
	@PostMapping(value = "/orderpay")
	public ResponseResult<Map<String, String>> orderPay(@RequestHeader(value = "token", required = true) String token,
			@RequestHeader(value = "deviceNum", required = false) String deviceNum, HttpServletRequest request,
			@RequestBody @Valid OrderPayCreateVo createVo, BindingResult bindingResult) {
		ResponseResult<Map<String, String>> result = new ResponseResult<>();
		try {
			// 根据token获取用户信息
			UserVo user = tokenUtil.getUser(token);
			createVo.setOperateId(user.getUserId());
			createVo.setCpuSerial(deviceNum);
			createVo.setIp(IpUtil.getIpAddr(request));

			result.success(JSON.parseObject(paymentBffService.getOrderPay(createVo), Map.class));
		} catch (BizException e) {
			logger.error("[orderPay]生成预支付单异常:", e);
			result.error(e.getExceptionCode() == null ? ResponseCodeEnum.UNKNOWN_ERROR.getCode() : e.getExceptionCode(),
					e.getMessage());
		} catch (Exception e) {
			logger.error("[orderPay]生成预支付单异常:", e);
			result.error(ResponseCodeEnum.UNKNOWN_ERROR.getCode(), "生成预支付单异常");
		}
		return result;
	}

	@Override
	@ApiOperation(value = "智能终端支付结果")
	@PostMapping(value = "/aio/result")
	public ResponseResult<PaymentResultVo> aioPaymentResult(
			@RequestHeader(value = "token", required = true) String token,
			@RequestHeader(value = "deviceNum", required = false) String deviceNum,
			@RequestBody @Valid AioPayResultModifyVo modifyVo, BindingResult bindingResult) {
		ResponseResult<PaymentResultVo> result = new ResponseResult<>();
		try {
			// 根据token获取用户信息
			// UserVo user = tokenUtil.getUser(token);
			modifyVo.setCpu(deviceNum);
			result.success(paymentResultBffService.modifyAioPayResult(modifyVo));
		} catch (BizException e) {
			logger.error("[aioPaymentResult]智能终端支付结果异常:", e);
			result.error(e.getExceptionCode() == null ? ResponseCodeEnum.UNKNOWN_ERROR.getCode() : e.getExceptionCode(),
					e.getMessage());
		} catch (Exception e) {
			logger.error("[aioPaymentResult]智能终端支付结果异常:", e);
			result.error("智能终端支付结果异常");
		}
		return result;
	}

	@Override
	@ApiOperation(value = "查询支付结果")
	@ApiImplicitParams({ @ApiImplicitParam(name = "orderCode", value = "订单号", required = true, dataType = "Long"),
			@ApiImplicitParam(name = "scheduleId", value = "排期id(还款传)", required = false, dataType = "Integer"),
			@ApiImplicitParam(name = "costType", value = "支付类型（1：订购，2：续订，3：加购，4：结算，5：还款，6：退租缴费）", required = true, dataType = "Integer") })
	@GetMapping(value = "/result")
	public ResponseResult<PaymentResultVo> paymnetResult(@RequestHeader(value = "token", required = true) String token,
			Long orderCode, Integer scheduleId, Integer costType) {
		ResponseResult<PaymentResultVo> result = new ResponseResult<>();
		try {
			// 根据token获取用户信息
			// UserVo user = tokenUtil.getUser(token);
			if (costType == null && scheduleId != null && scheduleId > 0) {
				costType = 5;
			}
			result.success(paymentResultBffService.getPaymentResult(orderCode, scheduleId,
					PaymentCostTypeEnum.getEnum(costType)));

		} catch (BizException e) {
			logger.error("[paymnetResult]查询支付结果异常:", e);
			result.error(e.getExceptionCode() == null ? ResponseCodeEnum.UNKNOWN_ERROR.getCode() : e.getExceptionCode(),
					e.getMessage());
		} catch (Exception e) {
			logger.error("[paymnetResult]查询支付结果异常:", e);
			result.error("查询支付结果异常");
		}
		return result;
	}

	@Override
	@ApiOperation(value = "查询支付记录")
	@GetMapping(value = "/record/list")
	public ResponseResult<List<PaymentRecordVo>> paymentRecord(
			@RequestHeader(value = "token", required = true) String token) {
		ResponseResult<List<PaymentRecordVo>> result = new ResponseResult<>();
		try {
			// 根据token获取用户信息
			UserVo user = tokenUtil.getUser(token);
			result.success(paymentBffService.getPaymentRecord(user.getUserId()));

		} catch (BizException e) {
			logger.error("[paymentRecord]查询支付记录异常:", e);
			result.error(e.getExceptionCode() == null ? ResponseCodeEnum.UNKNOWN_ERROR.getCode() : e.getExceptionCode(),
					e.getMessage());
		} catch (Exception e) {
			logger.error("[paymentRecord]查询支付记录异常:", e);
			result.error("查询支付记录异常");
		}
		return result;
	}
}
